// by Xeno

private ["_dir_to_set","_m_name","_marker","_d_mgnest_pos","_exit_it","_m_text"];

if ((player getVariable "d_mgnest_available")== 0) exitWith{"You cannot build MGNests anymore!" call XfGlobalChat};
if (d_player_busy_building) exitWith{"You are already busy..." call XfGlobalChat};
if ((player call XfGetHeight) > 5) exitWith {"You must be kidding..." call XfGlobalChat};

_d_mgnest_pos = player GetVariable "d_mgnest_pos";
if (count _d_mgnest_pos > 0) exitWith {"You have already placed a mg nest. You have to remove it to build a new one." call XfGlobalChat};

_d_mgnest_pos = player modeltoworld [0,2,0];

if (surfaceIsWater [_d_mgnest_pos select 0, _d_mgnest_pos select 1]) exitWith {
	"It is not possible to place a mg nest into water." call XfGlobalChat;
};
d_player_busy_building = true;

_helper1 = "HeliHEmpty" createVehicleLocal [_d_mgnest_pos select 0, (_d_mgnest_pos select 1) + 4, 0];
_helper2 = "HeliHEmpty" createVehicleLocal [_d_mgnest_pos select 0, (_d_mgnest_pos select 1) - 4, 0];
_helper3 = "HeliHEmpty" createVehicleLocal [(_d_mgnest_pos select 0) + 4, _d_mgnest_pos select 1, 0];
_helper4 = "HeliHEmpty" createVehicleLocal [(_d_mgnest_pos select 0) - 4, _d_mgnest_pos select 1, 0];

_exit_it = false;
if ((abs (((getPosASL _helper1) select 2) - ((getPosASL _helper2) select 2)) > 2) || (abs (((getPosASL _helper3) select 2) - ((getPosASL _helper4) select 2)) > 2)) then {
	"Place not valid. Try another location to place the mg nest." call XfGlobalChat;
	_exit_it = true;
};

for "_mt" from 1 to 4 do {call compile format ["deleteVehicle _helper%1;", _mt]};

if (_exit_it) exitWith {d_player_busy_building = false;};

for "_ic" from 1 to mg_nest_build_duration do {
	player playMove "AinvPknlMstpSlayWrflDnon_medic";
	sleep 3;
	waitUntil {animationState player != "AinvPknlMstpSlayWrflDnon_medic"};
	if (!(alive player)) exitWith {};
};
d_player_busy_building = false;
if (!(alive player)) exitWith {"You died before your MG nest was ready." call XfGlobalChat};

_dir_to_set = getdir player;

player SetVariable ["d_mgnest_pos", _d_mgnest_pos];

_mg_nest = createVehicle [d_mg_nest, _d_mgnest_pos, [], 0, "NONE"];
_mg_nest setdir _dir_to_set;
[_mg_nest, 0] call XfSetHeight;

player SetVariable ["mg_nest", _mg_nest];
player reveal _mg_nest;

"MG Nest ready." call XfGlobalChat;
_m_name = format ["MG Nest %1", str(player)];
_m_text = format ["MG Nest %1", name(player)]; 
["d_p_o_a", [str(player), [_mg_nest,_m_name,name player,playerSide,_m_text]]] call XNetCallEvent;

_mg_nest addAction ["Remove MG Nest" call XRedText, "client\removemgnest.sqf"];
_mg_nest addEventHandler ["killed",{[_this select 0] spawn XMGnestKilled}];

player moveInGunner _mg_nest;